package fr.ul.ade.secunde.ui.phone;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import fr.ul.ade.R;
import fr.ul.ade.secunde.database.AdeWebContract;
import fr.ul.ade.secunde.ui.HelpActionListener;
import fr.ul.ade.secunde.ui.PreferencesActionListener;
import fr.ul.ade.secunde.ui.ScheduleActionListener;
import fr.ul.ade.secunde.ui.ScheduleDetailsFragment;
import fr.ul.ade.secunde.ui.ScheduleListFragment;
import fr.ul.ade.secunde.ui.tablet.MainActivity;
import fr.ul.ade.secunde.util.Bundles;

/**
 * Activité responsable de la liste des emplois du temps (affichage et mise à
 * jour).
 * 
 * @author Michaël Schnell
 * @since Jul 2, 2013
 * 
 * @version 1.7
 */
public class ScheduleList
		extends SherlockFragmentActivity
		implements ScheduleActionListener, PreferencesActionListener,
		HelpActionListener {

	private boolean createActionMode;

	private long scheduleDetailsId;
	private String scheduleDetailsName;

	protected ActionMode mActionMode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// TODO A supprimer
		// Development.fillProjects(this);
		// Development.fillSchedules(this);
		// Development.fillLessons(this);

		/*
		 * Si on est sur une tablette, on lance l'activité responsable pour la
		 * version tablette (MainActivity) et on termine cette activité, sinon
		 * on continue l'exécution
		 */
		if (isTablet()) {
			this.startActivity(new Intent(this, MainActivity.class));
			this.finish();
			return;
		}

		this.setContentView(R.layout.activity_schedule_list);
		if (savedInstanceState == null) {
			final FragmentTransaction transaction = this
					.getSupportFragmentManager().beginTransaction();
			transaction.add(R.id.schedule_list_fragment_container,
					ScheduleListFragment.newInstance());
			transaction.commit();
			this.createActionMode = false;
		} else {
			this.createActionMode = savedInstanceState
					.getBoolean(Bundles.SCHEDULE_DETAILS_ACTION_MODE, false);

			if (this.createActionMode) {
				this.startActionMode(savedInstanceState
						.getLong(Bundles.SCHEDULE_DETAILS_ID),
						savedInstanceState
								.getString(Bundles.SCHEDULE_DETAILS_NAME));
			}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean(Bundles.SCHEDULE_DETAILS_ACTION_MODE,
				this.createActionMode);
		if (this.createActionMode) {
			outState.putLong(Bundles.SCHEDULE_DETAILS_ID,
					this.scheduleDetailsId);
			outState.putString(Bundles.SCHEDULE_DETAILS_NAME,
					this.scheduleDetailsName);
		}
		super.onSaveInstanceState(outState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		this.getSupportMenuInflater().inflate(R.menu.schedule_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_create:
			this.showCreateForm();
			return true;

		case R.id.action_sync_all:
			// FIXME Synchronisation de tous les emplois du temps
			Toast.makeText(this, "Synchronisation", Toast.LENGTH_SHORT).show();
			return true;

		case R.id.action_preferences:
			this.showPreferences();
			return true;

		case R.id.action_help:
			this.showHelp();
			return true;

		default:
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		this.createActionMode = false;
	}

	/*
	 * Actions sur les emplois du temps.
	 */
	@Override
	public void showCreateForm() {
		this.startActivity(new Intent(this, CreateSchedule.class));
	}

	@Override
	public void showEditForm(long scheduleId) {
		this.startActivity(new Intent(this, EditSchedule.class)
				.putExtra(Bundles.SCHEDULE_ID, scheduleId));
	}

	@Override
	public void showDeleteForm(final long scheduleId, final String scheduleName) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.schedule_details_delete_dialog_title)
				.setMessage(this
						.getResources()
						.getString(R.string.schedule_details_delete_dialog_text,
								scheduleName));
		builder.setIcon(RESULT_OK);

		// Valider la suppression
		builder.setPositiveButton(R.string.schedule_details_delete_dialog_yes,
				new DialogInterface.OnClickListener() {
					// Supression de l'edt
					@Override
					public void onClick(DialogInterface dialog, int which) {
						final ScheduleList sl = ScheduleList.this;
						sl.getContentResolver().delete(AdeWebContract.Schedule
								.buildUri(scheduleId),
								null,
								null);
						dialog.dismiss();
						sl.mActionMode.finish();
					}// onClick(DialogInterface, int)
				});

		// // Annuler la suppression
		builder.setNegativeButton(R.string.schedule_details_delete_dialog_cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}// onClick(DialogInterface, int)
				});
		Dialog dialog = builder.create();
		dialog.show();
	}

	@Override
	public void showScheduleDetails(long scheduleId, String scheduleName) {
		this.scheduleDetailsId = scheduleId;
		this.scheduleDetailsName = scheduleName;
		this.showDetailsFragment(scheduleId, scheduleName);
		this.startActionMode(scheduleId, scheduleName);
	}

	/**
	 * @param scheduleId
	 */
	public void showDetailsFragment(long scheduleId, String scheduleName) {
		final FragmentManager fm = this.getSupportFragmentManager();
		final FragmentTransaction transaction = fm.beginTransaction();
		transaction.setCustomAnimations(android.R.anim.fade_in,
				android.R.anim.fade_out);

		final Fragment listFragment = fm
				.findFragmentById(R.id.schedule_list_fragment_container);
		transaction.hide(listFragment);
		transaction.remove(listFragment);

		final Fragment detailsFragment = ScheduleDetailsFragment
				.newInstance(scheduleId, scheduleName);
		transaction.add(R.id.schedule_list_fragment_container, detailsFragment);
		transaction.show(detailsFragment);

		transaction.addToBackStack(null);

		transaction.commit();
	}

	@Override
	public void showLessonList(long scheduleId) {
		this.startActivity(new Intent(this, LessonList.class)
				.putExtra(Bundles.SCHEDULE_ID, scheduleId));
	}

	@Override
	public void showPreferences() {
		this.startActivity(new Intent(this, Preferences.class));
	}

	@Override
	public void showNotificationsForm() {
		/*
		 * Do nothing, it is impossible to reach the notifications form from
		 * this activity.
		 */
	}

	@Override
	public void showHelp() {
		// TODO Auto-generated method stub
	}

	/*
	 * Méthodes auxiliaires.
	 */

	private boolean isTablet() {
		return (this.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	private void startActionMode(long scheduleId, String scheduleName) {
		this.createActionMode = true;
		this.mActionMode = this.startActionMode(new ScheduleDetailsActionMode(
				this, scheduleId, scheduleName));
	}

}// class SchedeuleList